package com.o2o.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.o2o.dto.ShopExecution;
import com.o2o.entity.Area;
import com.o2o.entity.PersonInfo;
import com.o2o.entity.Shop;
import com.o2o.entity.ShopCategory;
import com.o2o.enums.ShopStateEnum;
import com.o2o.service.ShopService;
import com.o2o.utils.HttpServletRequestUtil;
import com.o2o.utils.ImageUtil;
import com.o2o.utils.PathUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * package_name:com.o2o.controller
 * Author:徐亚远
 * Date:2019/11/27 21:41
 * 项目名:o2o
 * Desription:
 **/
@Controller
public class ShopController {
    @Autowired
    private ShopService shopService;
    @RequestMapping("/shopInsert")
    @ResponseBody
    public String shopInsert(){
        Shop shop = new Shop();
        PersonInfo owner = new PersonInfo();
        Area area = new Area();
        ShopCategory shopCategory  = new ShopCategory();
        owner.setUserId(1L);
        area.setAreaId(2);
        shopCategory.setShopCategoryId(1L);
        shop.setOwner(owner);
        shop.setArea(area);
        shop.setShopCategory(shopCategory);
        shop.setShopName("新版测试11/29");
        shop.setShopDesc("徐老头");
        shop.setShopAddr("河南");
        shop.setPhone("15225200721");
        shop.setPriority(1);
        shop.setCreateTime(new Date());
        shop.setEnableStatus(1);
        shop.setAdvice("小店不错");
        shop.setLastEditTime(new Date());
        int ss = shopService.shopInsert(shop);
        //assertEquals(1,ss);
        System.out.println(ss);
        return  "success";
    }
   @RequestMapping(value = "/registShop",method = RequestMethod.GET)
    @ResponseBody
    private Map<String,Object> registShop(HttpServletRequest request) throws IOException {
        Map<String,Object> modelMap = new HashMap<>();
        /*接受并转换相应的参数,包括店铺信息以及图片信息*/
        String shopStr =HttpServletRequestUtil.getString(request,"shopStr" );
        ObjectMapper mapper = new ObjectMapper();
        Shop shop = null;
        try {
            shop = mapper.readValue(shopStr,Shop.class);
            System.out.println("jfdshfkjdsh徐亚远:"+shop);
        }catch (Exception E){
            modelMap.put("success",false );
            modelMap.put("errmsg", E.getMessage() );
            return modelMap;
        }
        CommonsMultipartFile shopImg = null;
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
     if(commonsMultipartResolver.isMultipart(request)){
         MultipartHttpServletRequest multipartHttpServletRequest =
                 (MultipartHttpServletRequest)request;
         shopImg = (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg");
     }else {
         modelMap.put("success",false );
         modelMap.put("essMsg","上传图片不能为空" );
         return modelMap;
     }
     /*注册店铺*/
        if(shop !=null && shopImg !=null){
            PersonInfo owner = new PersonInfo();
            owner.setUserId(1L);
            shop.setOwner(owner);
            File shopImgFile = new File(PathUtil.getImageBasePath()+
                    ImageUtil.generateRandomFileName());
            shopImgFile.createNewFile();
            inputStreamToFile(shopImg.getInputStream(),shopImgFile );
            ShopExecution se = shopService.addShop(shop,shopImg );
            if (se.getState() == ShopStateEnum.CHECK.getState()){
                        modelMap.put("success",true );
            }else {
                modelMap.put("success",false );
                modelMap.put("essMsg","请输入店铺信息");
            }
            return modelMap;
        }else {
            modelMap.put("success",false );
            modelMap.put("errMsg","请输入店铺信息" );
            return modelMap;
        }
    }
    private static void inputStreamToFile(InputStream ins,File file) throws IOException {
        FileOutputStream os = null;
        try {
            os = new FileOutputStream(file);
            int bytesRead = 0;
            byte [] buffer = new byte[1024];
            while ((bytesRead = ins.read(buffer))!=-1){
                os.write(buffer,0,bytesRead);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException("调用inputStreamToFile产生异常:"+e.getMessage());
        }finally {
            try {
                if(os!=null){
                    os.close();
                }
                if(ins!=null){
                    ins.close();
                }
            }catch (IOException e){
                throw new RuntimeException("inputStreamToFile关闭IO异常:"+e.getMessage());
            }
        }
    }



/*
    @RequestMapping(value = "/registshop")
    @ResponseBody
    public Map<String, Object> registerShop(HttpServletRequest request) {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        // 1. 接收并转换相应的参数，包括shop信息和图片信息

        // 1.1 shop信息

        // shopStr 是和前端约定好的参数值，后端从request中获取request这个值来获取shop的信息
        String shopStr = HttpServletRequestUtil.getString(request, "shopStr");
        // 使用jackson-databind 将json转换为pojo
        ObjectMapper mapper = new ObjectMapper();
        Shop shop = null;
        try {
            // 将json转换为pojo
            shop = mapper.readValue(shopStr, Shop.class);
        } catch (Exception e) {
            e.printStackTrace();
            // 将错误信息返回给前台
            modelMap.put("success", false);
            modelMap.put("errMsg", e.getMessage());
        }

        // 1.2 图片信息 基于Apache Commons FileUpload的文件上传

        // Spring MVC中的 图片存在CommonsMultipartFile中
        CommonsMultipartFile shopImg = null;
        // 从request的本次会话中的上线文中获取图片的相关内容
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if (commonsMultipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            // shopImg是和前端约定好的变量名
            shopImg = (CommonsMultipartFile) multipartRequest.getFile("shopImg");
        } else {
            // 将错误信息返回给前台
            modelMap.put("success", false);
            modelMap.put("errMsg", "图片不能为空");
        }

        // 2. 注册店铺
        if (shop != null && shopImg != null) {
            // Session TODO
            // 店主persionInfo的信息，肯定要登录才能注册店铺。
            // 所以这部分信息我们从session中获取，尽量不依赖前端,这里暂时时不具备条件，后续改造，先硬编码，方便单元测试
            PersonInfo personInfo = new PersonInfo();
            personInfo.setUserId(1L);

            shop.setOwner(personInfo);
            // 注册店铺

            // se = shopService.addShop(shop, shopImg); 改造前的调用方式
            // 这个时候，我们从前端获取到的shopImg是CommonsMultipartFile类型的，如何将CommonsMultipartFile转换为file.
            // 网上也有将CommonsMultipartFile转换为File的方法，并通过maxInMemorySize的设置尽量不产生临时文件
            // 这里我们换个思路,因为CommonsMultipartFile可以获取InputStream,Thumbnailator又可以直接处理输入流
            // 因为InputStream中我们无法得到文件的名称，而thumbnail中需要根据文件名来获取扩展名，所以还要再加一个参数String类型的fileName
            // 既然第二个和第三个参数都是通过shopImg获取的，为什么不直接传入一个shopImg呢？
            // 主要是为了service层单元测测试的方便，因为service层很难实例化出一个CommonsMultipartFile类型的实例
            ShopExecution se = null;;
            try {
                se = shopService.addShop(shop, shopImg.getInputStream(), shopImg.getOriginalFilename());
                if (se.getState() == ShopStateEnum.CHECK.getState()) {
                    modelMap.put("success", true);
                    modelMap.put("errMsg", "注册成功");
                } else {
                    modelMap.put("success", false);
                    modelMap.put("errMsg", se.getStateInfo());
                }
            } catch (IOException e) {
                e.printStackTrace();
                modelMap.put("success", false);
                modelMap.put("errMsg", "addShop Error");
            }
        } else {
            // 将错误信息返回给前台
            modelMap.put("success", false);
            modelMap.put("errMsg", "请输入店铺信息");
        }
        return modelMap;
    }*/

}